//
//  OssUpload.m
//  KangarooDoctor
//
//  Created by 廖罡 on 2024/2/1.
//

#import "OssUpload.h"
#import <AFNetworking/AFNetworking.h>
#import "HttpPostMultipart.h"


@implementation OssUpload

#if DEBUG
//+(NSDictionary*)connectionProxyDictionary
//{
//    NSString* host = @"192.168.5.4";
////    NSString* host = @"127.0.0.1";
//    
//    NSNumber* port = [NSNumber numberWithInt: 8888];
//    return @{
//        @"HTTPEnable":@(1),
//        (NSString*)kCFStreamPropertyHTTPProxyHost: host,
//        (NSString*)kCFStreamPropertyHTTPProxyPort: port,
//        
//        @"HTTPSEnable":@(1),
//        (NSString*)kCFStreamPropertyHTTPSProxyHost: host,
//        (NSString*)kCFStreamPropertyHTTPSProxyPort: port,
//        
//    };
//}
#endif

+(void)uploadWithUrl:(NSString*)urlString
         accessKey:(NSString*)accessKey
            policy:(NSString*)policy
            signature:(NSString*)signature
            expire:(NSString*)expire
               dir:(NSString*)dir
              data:(NSData*)data
            callback:(ApiCallback)callback
{
    NSTimeInterval t = time(nil);
    
    NSString *key = [NSString stringWithFormat:@"%@%u.png", dir, (uint32_t)t];
    
    NSString *fileName = [NSString stringWithFormat:@"%u.png", (uint32_t)t];
    
    NSDictionary *p = @{
        @"OSSAccessKeyId": accessKey,
        @"policy": policy,
        @"signature": signature,
        @"key": key,
        @"success_action_status": @"200",
        @"expire": expire,
    };

    HttpPostMultipart *request = [[HttpPostMultipart alloc]initWithUrl:urlString];
    
    // Add user-agent
    [request addHeader:@"User-Agent" value:@"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.132 Safari/537.36"];
    // Add field
    
    for (NSString *key in p) {
        [request addFormField: key value:p[key]];
    }
    
    // Add a image
//    [request addFormFile:@"file" path:fileName];

    [request addFormFileData:nil data:data];
    
    void (^completionHandler)(NSData *, NSURLResponse *, NSError *) = ^(NSData *data, NSURLResponse *response, NSError *error) {
        
        if (error) {
            NSLog(@"Error: %@", error);
            callback(nil, error.debugDescription);
        } else {
//            NSLog(@"%@ %@", response, responseObject);
            NSHTTPURLResponse *httpResp = (NSHTTPURLResponse *)response;
            if (httpResp.statusCode == 200) {
                //ok
                NSString *resultUrl = [NSString stringWithFormat:@"%@/%@", urlString, key];
                
                callback(resultUrl, nil);
            }else{
                callback(nil, @"not 200");
            }
            
        }
        
    };
    
    [request finish:completionHandler];
    
}

@end
